'use strict';
/*
* 
* 
*
*
*
*
*
*/
angular.module('spLoad',[]).service('loadingService',['$rootScope',function($rootScope){
	var _observeList = {};
	var _LoadingList = {};
	var _addUrl = function(url){
		_observeList[url] = true;
	};
	var _testUrl = function(url){
		return !!_observeList[url];
	};
	var regLoad = function(url){
		_LoadingList[url] = true;
		if(_observeList[url]){
			$rootScope.$broadcast('loadingStart',url);
		}
	};
	var regUnload = function(url){
		_LoadingList[url] = false;
		if(_observeList[url]){
			$rootScope.$broadcast('loadingEnd',url);
		}
	};
	var isLoading = function(url){
		return _LoadingList[url];
	};
	return {addUrl:_addUrl,testUrl:_testUrl,regLoad:regLoad,regUnload:regUnload,isLoading:isLoading};

}])
.directive('spLoading',["loadingService",function(loadingService){
  return{
    restrict: 'A',
    priority : 10,
    link: function(scope,element,attrs){
      loadingService.addUrl(attrs.spLoading); 
      if(loadingService.isLoading(attrs.spLoading)){
      	element.addClass('spLoading');
      }
      scope.$on('loadingStart',function(e,u){
        if(u == attrs.spLoading){
          element.addClass('spLoading');
          var cs=attrs.npLoadingSize+"px "+attrs.npLoadingSize+"px";
          element.css("background-size",cs);
        }
      });
      scope.$on('loadingEnd',function(e,u){
        if(u == attrs.spLoading){
          element.removeClass('spLoading');
        }
      });
    }
  };
}])
.factory('LoadInterceptor', ["$q","loadingService",function ($q,loadingService) {
	    return {
	          request:function(config){
	              // config.headers["TOKEN"] = $rootScope.user.token;
			      var url = config.url.split('?')[0];
			      // console.log(url);
			      loadingService.regLoad(url);
	              return config;
	          },
	          response: function(response) {
			      // do something on success
			      var url = response.config.url.split('?')[0];
			      loadingService.regUnload(url);
			      return response;
			   }
	    };
	 }])
.config(function ($httpProvider) {
    	$httpProvider.interceptors.push('LoadInterceptor');
});